<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/11/29
 * Time: 16:08
 */
namespace App\Http\Controllers\Home;
use App\Http\Controllers\Controller;
use App\Models\StockActivity;
use App\Models\StockOrder;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Validator;
use App\Repositories\MemberRepositoryEloquent;
class ActivityController extends Controller
{

    protected $user;

    public function __construct(MemberRepositoryEloquent $user)
    {
        //parent::__construct();
        $this->user = $user;

    }
    /*
     * 首页活动列表
     * */
    public function index()
    {
        //$activity=StockActivity::find_all_activity();
        //$activity = StockActivity::limit(5)->orderBy('id','desc')->get();
        $activity = StockActivity::where('status','<',2)->withCount(['orders' => function ($query) {
                        $query->where('status', '<', 2);
                    }])->orderBy('orders_count','desc')->simplePaginate(5);
        

        return view('home.activity.index',['activity'=>$activity]);
    }

    /**
     * [Activity 新增活动 Jy]
     * @param Request $request [description]
     */
    public function addActivity(Request $request)
    {   
        $user =  Auth::user();
        //活动天数
        $day=1;
        //判断是否是员工
        return view('home.activity.addActivity',compact('user'));
    }

    /**
     * [storeActivity 存储活动]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function storeActivity(Request $request){
        $user =  Auth::user();
        //dd(1);
         $validator = Validator::make($request->all(), [
            'name' => 'required|max:255',
            'money' => 'required|numeric|min:1|max:10',
            'activity_time' => 'required',
        ],['activity_time.required'=>'请选择有效的活动时间']);

       
        $time = $request->activity_time;
        $validator->after(function($validator) use ($time,$user) {

            //判断是否是经纪人
            
            if($user->is_agent!=1){
                $validator->errors()->add('name', '无权发起活动!');
            }
            
            $datetime=strtotime($time);
           
            //判断是否是休市日期
            
            $beginDate = date('Ymd',$datetime);
            $beginDate = date('Ymd',$datetime);
           $response = get_trade_data($beginDate,$beginDate);
           if($response->retCode==1){
                $newtrade=array_pop($response->data);
                if($newtrade->isOpen==0){
                    $validator->errors()->add('activity_time', '不能选择休市日期!');
                }
            }else{
                $validator->errors()->add('activity_time', '请求错误!');
            }
            
             //判断是否是当日
            $data['start_time']=mktime(9,00,00,date('m',$datetime),date('d',$datetime),date('Y',$datetime));
            if($datetime<time()+600){
                $validator->errors()->add('activity_time', '股市即将开盘，不能开启当日活动！');
            }

        });

         if ($validator->fails()) {
            return redirect('/addstockactivity')
                        ->withErrors($validator)
                        ->withInput();
        }

        //写入活动
        $data['name'] = $request->name;
        $data['user_id'] = $user->id;
        $data['profile'] = $request->profile;
        $data['money'] = $request->money;
        $datetime=strtotime($time);
        $data['start_time']=mktime(9,00,00,date('m',$datetime),date('d',$datetime),date('Y',$datetime));
        $data['end_time']=mktime(15,05,00,date('m',$datetime),date('d',$datetime),date('Y',$datetime));
        $data['status'] = 0;
        $activity = StockActivity::create($data);
        return redirect(url('/show_activity', ['activity_id' => $activity->id]));

    }

    /*
     * 微信分享
     * */
    public function share()
    {
        return view();
    }

    /*
     * 订单详情
     * $id活动的id
     * */
    public function show_activity($id)
    {
        $activity=StockActivity::find_activity($id);
        //$people=StockOrder::where('stock_activity_id',$id)->count();
        //$total_price=StockOrder::where('stock_activity_id',$id)->sum('pay_money');
        
        $orders = $activity->orders()->where('status','=',1)->get();
        
        $people=$orders->count();
        $total_price= $orders->sum('pay_money');

        $activity->people=$people;
        $activity->total_price=$total_price;

        if($activity->status==1){
            $codes = $orders->pluck('stock_code');
            $codes =  $codes->unique();
            $codes = implode(',',$codes->all());
            $res = get_detail_data($codes);
            $datas = collect($res);
            //var_dump(collect($res)->toArray());
            
            $datas = $datas->keyBy('ticker');
            //dd($datas);
            foreach($orders as $k=>$order){
                //echo $k.'-'.$order->stock_name.'<hr>';
                 $data = null;
                // $filtered = $datas->where('ticker', $order->stock_code)->where('shortNM', $order->stock_name);
                // $data =$filtered->first();
                if(isset($datas[$order->stock_code])){
                    $data = $datas[$order->stock_code];
                }
                
                //dd($data);
                if(!$data){
                    continue;
                }

                $open_price = $data->openPrice;
                //dd($open_price);
                $order->open_price = $open_price;
                if($order->open_price>0){
                    $order->close_price = $data->lastPrice;
                }else{
                    $order->close_price = 0.00;
                }
                
                //$yeild = round(($data->lastPrice-$data->openPrice)/$data->lastPrice,6);
                if(!empty($order->close_price)){
                    //$yield = sprintf("%.4f",(($data->lastPrice-$data->openPrice)/$data->openPrice)*100);
                    $yield = sprintf("%.4f",(($order->close_price-$order->open_price)/$order->open_price)*100);
                }else{
                    $yield = 0.00;
                }
                
                $order->yield = $yield;
                

                $orders[$k] = $order;
            }
        }else{

        }

        
        $orders = $orders->sortByDesc("yield")->values();
        $wechat = app('wechat');
        $js = $wechat->js;
        return view('home.activity.activityListInfo',['activity'=>$activity,'orders'=>$orders,'js'=>$js]);
    }

    
    /*
     * 订单创建
     * */
    public function create_order(Request $request)
    {   
        if(empty(Auth::user())){
            return response()->json(['status'=>1,'msg'=>'请先登录参与活动！']);
        }
        $code=$request->get('code');
        $money=$request->get('money');
        $activity_id=$request->get('activity_id');
        $activityData=StockActivity::find_activity($activity_id);
        if($activityData->start_time<time()){
            return response()->json(['status'=>1,'msg'=>'活动已开始,请参与其他活动']);
        }
        $time=date('Ymd',$activityData->start_time);

        //判断是否是有效的股票
        $codeData=get_detail_data($code);
        $codeData=collect($codeData)->first();
        //$data =$filtered->first();
        if($codeData){
            $codeName=$codeData->shortNM;
        }else{
            return response()->json(['status'=>1,'msg'=>'请填写正确的股票代码']);
        }


        //判断当前股票是否处于停牌
        // $bondBack=get_bond_data($code);
        // if($bondBack->retCode==1){
        //     $newbond=array_pop($bondBack->data);
        //     if($newbond || $newbond->haltEndTime>date('Y-m-d')){
        //         return response()->json(['status'=>1,'msg'=>'该股票处于停牌状态,不能参与活动'],200);
        //     }
        // }
        //判断活动时间是否休市
        $tradeBack=get_trade_data($time,$time);
        if($tradeBack->retCode==1){
            $newtrade=array_pop($tradeBack->data);
            if($newtrade->isOpen==0){
                return response()->json(['status'=>1,'msg'=>'休市期间，如有疑问请联系客服!'],200);
            }
        }
        //判断当前股票是否是新股
        $newBack=get_new_data($code);
        if($newBack->retCode==1){
            if($newBack->data[0]->listDate>date('Y-m-d',strtotime('-2 weeks'))){
                return response()->json(['status'=>1,'msg'=>'该股票是新股,不能参与活动']);
            }
        }

        if(StockOrder::where('user_id','=',Auth::user()->id)->where('stock_activity_id','=',$activity_id)->where('status','=',1)->where('stock_code','=',$code)->first()){
             return response()->json(['status'=>1,'msg'=>'你已购买过相同股票！']);
        }

        $data=['out_trade_no'=>date('YmdHis').Auth::user()->id.rand(100,900),'stock_name'=>$codeName,'stock_code'=>$code,'stock_activity_id'=>$activity_id,'money'=>$money,'pay_money'=>$money,'status'=>0,'user_id'=>Auth::user()->id];
        $res=StockOrder::create($data);
        if($res){
            return response()->json(['status'=>0,'id'=>$res->id]);
        }

    }

    public function sure_pay($id)
    {
        $order=StockOrder::find_by_id($id);
        $activity=StockActivity::find_activity($order->stock_activity_id);
        return view('home.activity.sureOrderPay',compact('order','activity'));
    }

    public function pay(Request $request){
        $money=$request->get('money');
        $money = abs($money);
        $id=$request->get('id');
        $orderData=StockOrder::find_by_id($id);
        $userdata=User::find($orderData->user_id);
        if($userdata->balance<$money){
            return response()->json(['status'=>1,'msg'=>'余额不足,请及时充值'],200);
        }
        if($orderData->status==1){
            return response()->json(['status'=>1,'msg'=>'订单已支付'],200);
        }
        //$res=User::where(['id'=>$userdata->id])->decrement('balance', $money);
        $note = $orderData->money."元购买".$orderData->stock_name.'('.$orderData->stock_code.')';
        $res = $this->user->modifyBalance($userdata->id,-$money,3,$note);
        if($res){
            $result=StockOrder::update_order($id,['status'=>1,'pay_money'=>$money,'payment_time'=>date('Y-m-d H:i:s')]);
            if($result){
                return response()->json(['status'=>0,'msg'=>'恭喜您参与成功,请前往订单详情查看','id'=>$orderData->stock_activity_id],200);
            }
        }
        return response()->json(['status'=>0,'msg'=>'下单失败','id'=>$orderData->stock_activity_id],200);
    }


    public function rules($id){
         $activity=StockActivity::find($id);
        $wechat = app('wechat');
        $js = $wechat->js;
        return view('home.activity.rules',compact('js','id','activity'));
    }

}